import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
import notification from 'ant-design-vue/es/notification'
import { VueAxios } from './axios'
import { ACCESS_TOKEN } from '@/store/mutation-types'

// 创建 axios 实例
const service = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL, // api base_url
  timeout: 30000 // 请求超时时间
})

const err = (error) => {
  if (error.response &&
    // 没有 "静默" || 有 "静默" 但是 "静默" 为 否
    (!error.config.hasOwnProperty('silent') || (error.config.hasOwnProperty('silent') && !error.config.silent))) {
    const data = error.response.data
    const token = Vue.ls.get(ACCESS_TOKEN)
    switch (error.response.status) {
      case 400:
        notification.error({ meesage: '请求发生错误', description: data.message })
        break
      case 403:
        notification.error({ message: '没有权限', description: data.message })
        window.location.href = process.env.BASE_URL
        break
      case 401:
        if (token) {
          store.dispatch('Logout').then(() => {
            setTimeout(() => {
              window.location.reload()
            }, 1500)
          })
        } else {
          window.location.reload()
        }
        break
      case 422:
        const errMsg = Object.values(data.errors).reduce((msg, errorArr) => {
          errorArr.forEach(item => msg.push(item))
          return msg
        }, [])
        notification.error({
          message: '提交参数错误',
          description: errMsg.join(';')
        })
        break
      case 500:
        notification.error({
          message: '服务器发生错误',
          description: error.response.data.message
        })
        break
    }
  }
  return Promise.reject(error)
}

// request interceptor
service.interceptors.request.use(config => {
  const token = Vue.ls.get(ACCESS_TOKEN)
  if (token) {
    config.headers['Authorization'] = 'Bearer ' + token // 让每个请求携带自定义 token 请根据实际情况自行修改
  }
  return config
}, err)

// response interceptor
service.interceptors.response.use((response) => {
  // 刷新快到期的 token
  // try {
  //   const tokenInfo = Vue.ls.get(ACCESS_TOKEN_INFO)
  //   const whiteList = ['/auth']
  //   if (tokenInfo &&
  //       !whiteList.includes(response.config.url) &&
  //       moment().isAfter(moment(tokenInfo.expired_at).subtract(15, 'm'))) {
  //     store.dispatch('RefreshToken')
  //   }
  // } catch (e) {
  //   console.error(e)
  // }

  if (response.config.responseType === 'blob') {
    // 异步导出的情况 没有下载
    if (response.config.hasOwnProperty('params') && response.config.params.hasOwnProperty('async')) {
      return response.data
    }

    const a = document.createElement('a')
    a.style.display = 'none'
    a.href = window.URL.createObjectURL(new Blob([response.data]))
    a.setAttribute('download', decodeURI(response.headers['content-disposition'].split('utf-8\'\'')[1]))
    document.body.appendChild(a)
    a.click() // 执行下载
    window.URL.revokeObjectURL(a.href)
    document.body.removeChild(a)
  }

  return response.data
}, err)

const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, service)
  }
}

export {
  installer as VueAxios,
  service as axios
}
